let express = require('express');
let router = express.Router();
const {sleep, createFormData} = require("../util");
const {axiosQianxun, axiosServer} = require("../myAxios");
const axios = require("axios");

let retry = 0

async function thread () {
    while (true) {
        try {
            // console.log('执行', new Date().getTime())
            let res = await axiosServer.get('/wx/get-msg-send-task')
            if (res.data.code && res.data.data) {
                let data = res.data.data
                console.log('开始发送消息', data)
                // 发送微信消息
                await axiosQianxun.post('', {
                    "type": "Q0001",
                    "data": {
                        "wxid": data.to,
                        "msg": data.msg
                    }
                })
                // 设置发送成功
                await axiosServer.get('/wx/set-msg-is-send', {params: {id: data.id}})
            }
            retry = 0
            await sleep(1000)
        } catch (e) {
            console.error('任务异常,重试', ++retry, e)
            await sleep(30000)
            if (retry >= 10) break
        }
    }
    // new Promise(async resolve => {
    //     resolve()
    // }).then(thread)
}

thread()

router.all('/hook', async (req, res) => {
    try {
        console.log('收到千寻消息,转发到服务器', req.body)
        let data = req.body.data
        let msgData = data.data
        if ([3, 49].includes(msgData.msgType)) {
            let formData = await createFormData(msgData.msg)
            const headers = formData.getHeaders();//获取headers
            let res = await axiosServer.post('/upload', formData, {headers})
            console.log('上传文件结束', res)
            req.body.data.data.msg = res.data.data[0].replaceAll('http://tuofei.oss-cn-shenzhen.aliyuncs.com/img/', '')
        }
        await axiosServer.post('/wx/hook', req.body)
        console.log('-------end----------')
        res.json({
            code: 1
        });
    } catch (e) {
        console.error('hook异常', e)
    }
});

const fs = require('fs');
const FormData = require('form-data');
router.get('/test', async (req, res) => {
    const localFile = fs.createReadStream('C:\\Users\\13301\\Documents\\DaenWxHookImg\\c0fbacd3a1d353e4e8a3ea7c507595b9.jpg');
    const formData = new FormData();
    formData.append('file', localFile);
    formData.append('userId', 2)
    const headers = formData.getHeaders();//获取headers
    //获取form-data长度
    formData.getLength(async function (err, length) {
        if (err) {
            return;
        }
        headers['content-length'] = length;
        let res = await axiosServer.post('/upload', formData, {headers})
        console.log('上传文件成功', res)
    })
});
// "[pic=C:\Users\13301\Documents\DaenWxHookImg\c0fbacd3a1d353e4e8a3ea7c507595b9.jpg,isDecrypt=1]"

module.exports = router;

// {
//     event: 10006,
//         wxid: 'wxid_kw9roi42fqv222',
//     data: {
//     type: 'D0004',
//         des: '转账事件',
//         data: {
//         fromWxid: 'jiangshan873217486',
//             msgSource: 1,
//             transType: 1,
//             money: '0.01',
//             memo: '',
//             transferid: '1000050001202306130011064945271',
//             invalidtime: '1686719249'
//     },
//     timestamp: '1686632852228',
//         wxid: 'wxid_kw9roi42fqv222',
//         port: 9999,
//         pid: 39036,
//         flag: '7777'
// }
// }
